package com.example.opengl.base

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.opengl.GLES20
import android.opengl.GLUtils
import android.opengl.Matrix
import com.android.baselibrary.app.MainApplication

/**
 * @author: Mr.You
 * @create: 2023-08-08 15:38
 * @description:
 **/
object OpenGLUtils {
    private var mRotateAgree = 0

    /**
     * Mvp矩阵变换
     */
    fun transform(programId: Int, ration: Float) {
        //定义modelMatrix
        val modelMatrix = getIdentityMatrix(16)
        //定义viewMatrix
        val viewMatrix = getIdentityMatrix(16)
        //定义projectMatrix
        val projectMatrix = getIdentityMatrix(16)

        mRotateAgree = (mRotateAgree + 2) % 360

        Matrix.rotateM(modelMatrix, 0, mRotateAgree.toFloat(), -1f, -1f, 1f)
        Matrix.setLookAtM(viewMatrix, 0, 0f, 5f, 10f, 0f, 0f, 0f, 0f, 1f, 0f)
        Matrix.frustumM(projectMatrix, 0, -ration, ration, -1f, 1f, 3f, 20f)

        //mvp矩阵变换
        val tempMatrix = getIdentityMatrix(16)
        val mvpMatrix = getIdentityMatrix(16)

        Matrix.multiplyMM(tempMatrix, 0, viewMatrix, 0, modelMatrix, 0)
        Matrix.multiplyMM(mvpMatrix, 0, projectMatrix, 0, tempMatrix, 0)

        val mvpIndex = GLES20.glGetUniformLocation(programId, "mvpMatrix")
        GLES20.glUniformMatrix4fv(mvpIndex, 1, false, mvpMatrix, 0)


    }
    private fun getIdentityMatrix(size: Int = 16, offset: Int = 0): FloatArray {
        val matrix = FloatArray(size)
        Matrix.setIdentityM(matrix, offset)
        return matrix
    }
    fun loadTexture(resIds: IntArray): IntArray {
        val option = BitmapFactory.Options()
        option.inScaled = false
        var bitmaps = arrayOfNulls<Bitmap>(resIds.size)
        var texturesId = IntArray(resIds.size)
        GLES20.glGenTextures(resIds.size, texturesId, 0)
        resIds.forEachIndexed { index, i ->
            bitmaps[index] = BitmapFactory.decodeResource(MainApplication.mainApplication.resources, i, option)

            //绑定纹理
            GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texturesId[index])
            GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR_MIPMAP_LINEAR)
            GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR)

            GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmaps[index], 0)
            //生成mip贴图
            GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D)
            //取消纹理绑定
            GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0)
            bitmaps[index]?.recycle()

        }
        return texturesId
    }
}